<template>
  <div>
    <start-act-main-form ref="startActMainForm" @submit="callFormSubmit"></start-act-main-form>
    <start-act-select-user ref="actUserSelect" @submit="callSelectUser"></start-act-select-user>
  </div>
</template>

<script>

import startActMainForm from "./startActMainForm.vue";
import startActApi from "@/api/start/activiti/core/startActApi";
import StartActSelectUser from "./actUser/startActSelectUser.vue";
import startActTools from "@/views/start/activiti/components/startActTools";

export default {
  name: "startActStart",
  components: {StartActSelectUser, startActMainForm},
  props: {
    startUserType: String,
    userId: String,
    startApplySuccess: Function
  },
  data() {
    return {
      modelId: null,
      procModel: null,
      form: {
        done: null,
        model: null,
      },
      selectUserLis: null,
    }
  },
  created() {

  },
  methods: {
    init(actModelKey) {
      startActApi.getStartProcDefDetail(actModelKey).then(res => {
        let data = res.data.data
        this.procModel = data;
        this.$emit("loadProcDetailSuccess", data)
        this.$nextTick(() => {
          this.$refs.startActMainForm.init(data.procFormConfig);
        })
      })
    },
    clear() {
      this.$refs.startActMainForm.resetForm();
      if(this.$refs.actUserSelect){
        this.$refs.actUserSelect.clearSelectUser()
      }
    },
    submit() {
      this.$refs.startActMainForm.submit();
    },
    callFormSubmit(formData, done) {
      this.form.done = done;
      this.form.model = formData;
      if (startActTools.taskIsCustomAuth(this.procModel.procTasks)) {
        let taskCandidateConfig = this.procModel.procTasks[0].taskConfig.act_task_candidate_user
        this.$refs.actUserSelect.show(taskCandidateConfig)
        return
      }
      this.callStartActProc()
    },
    callStartActProc() {
      let config = {}
      config.confirmButtonText = "确定"
      config.cancelButtonText = "取消"
      config.type = "warning"
      this.$confirm('您确定要提交此申请吗？', config).then(() => {
        let data = {}
        data.businessFormData = this.form.model;
        data.startUserType = this.startUserType
        data.userId = this.userId;
        data.nextTaskAuthUser = this.selectUserLis
        return startActApi.startApply(this.procModel.procDefKey, data)
      }).then(res => {
        if (this.startApplySuccess) {
          this.startApplySuccess()
          return
        }
        this.$message.success("提交成功")
        this.$emit("startActApplySuccess")
      }).finally(() => {
        if (this.form.done) {
          this.form.done()
        }
      })

    },
    callSelectUser(userList, done) {
      let list = [];
      for (const user of userList) {
        let item = {}
        item.userId = user.id;
        item.startUserType = user.startUserType;
        list.push(item)
      }
      this.selectUserLis = list;
      done();
      this.callStartActProc();
    },
  }
}
</script>

<style scoped>

</style>
